﻿using HY.Common;
using HY.Entity;
using HY.Service;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace HY.Web
{
    public class GlobalSupport
    {
        #region 私有属性

        /// <summary>
        /// 所有菜单信息（对菜单进行管理时，需清除缓存中的菜单信息，以便加载新的信息）
        /// </summary>
        private static List<SysModule> AllModules
        {
            get
            {
                var sysModules = WebHelper.GetCache(GlobalKey.Module) as List<SysModule>;
                if (sysModules == null)
                {
                    BaseService baseService = new BaseService();
                    sysModules = baseService.EFGetMany<SysModule>(s => s.IsDeleted == false).OrderBy(o => o.ModuleSort).ToList();
                    WebHelper.SetCache(GlobalKey.Module, sysModules, GlobalKey.Module_TimeOut, false);
                }
                return sysModules;
            }
        }

        /// <summary>
        /// 所有角色权限（对角色进行管理时，需清除缓存中的角色权限信息，以便加载新的信息）
        /// </summary>
        private static List<SysRoleModule> AllRoleModules
        {
            get
            {
                var sysRoleModules = WebHelper.GetCache(GlobalKey.RoleModule) as List<SysRoleModule>;
                if (sysRoleModules == null)
                {
                    BaseService baseService = new BaseService();
                    sysRoleModules = baseService.EFGetMany<SysRoleModule>(s => s.IsDeleted == false).ToList();
                    WebHelper.SetCache(GlobalKey.RoleModule, sysRoleModules, GlobalKey.RoleModule_TimeOut, false);
                }
                return sysRoleModules;
            }
        }

        #endregion

        #region 公共属性
        /// <summary>
        /// 当前登录用户信息
        /// </summary>
        public static V_UserInfo CurrentUser
        {
            get
            {
                var userCookies = WebHelper.GetCookie(GlobalKey.UserInfo);
                if (string.IsNullOrWhiteSpace(userCookies))
                    return null;
                else
                    return JsonConvert.DeserializeObject<V_UserInfo>(EncryptHelper.DesDecrypt(userCookies));
            }
            set
            {
                WebHelper.SetCookie(GlobalKey.UserInfo, EncryptHelper.DesEncrypt(JsonConvert.SerializeObject(value)));
            }
        }

        /// <summary>
        /// 当前用户权限能看到的菜单信息
        /// </summary>
        public static List<SysModule> MyMenus
        {
            get
            {
                var userinfo = CurrentUser;
                if (userinfo != null)
                {
                    if (userinfo.UserName == GlobalConfig.AdminUserName)
                        return AllModules.Where(w => w.ModuleType != 2).ToList();
                    else
                    {
                        var moduleIDs = AllRoleModules.Where(w => w.RoleID == userinfo.RoleID).Select(s => s.ModuleID).ToArray();
                        var sysModules = AllModules.Where(w => moduleIDs.Contains(w.ID) && w.ModuleType != 2).ToList();
                        return sysModules;
                    }
                }
                return new List<SysModule>();
            }
        }

        /// <summary>
        /// 当前用户权限能看到的菜单及按钮信息
        /// </summary>
        public static List<SysModule> MyModules
        {
            get
            {
                var userinfo = CurrentUser;
                if (userinfo != null)
                {
                    if (userinfo.UserName == GlobalConfig.AdminUserName)
                        return AllModules;
                    else
                    {
                        var moduleIDs = AllRoleModules.Where(w => w.RoleID == userinfo.RoleID).Select(s => s.ModuleID).ToArray();
                        var sysModules = AllModules.Where(w => moduleIDs.Contains(w.ID)).ToList();
                        return sysModules;
                    }
                }
                return new List<SysModule>();
            }
        }
        #endregion

        /// <summary>
        /// 权限验证
        /// </summary>
        /// <param name="moduleUrl">模块链接</param>
        /// <returns></returns>
        public static bool CheckAuthorize(string moduleUrl)
        {
            if (CurrentUser.UserName == GlobalConfig.AdminUserName)
                return true;
            var moduleid = AllModules.Where(w => w.ModuleUrl == moduleUrl).Select(s => s.ID).FirstOrDefault();
            if (moduleid != 0)
            {
                var roleMenuID = AllRoleModules.Where(w => w.ModuleID == moduleid && w.RoleID == CurrentUser.RoleID).Select(s => s.ID).FirstOrDefault();
                if (roleMenuID != 0)
                    return true;
            }
            return false;
        }

        /// <summary>
        /// 权限验证
        /// </summary>
        /// <param name="areaName"></param>
        /// <param name="controllerName"></param>
        /// <param name="actionName"></param>
        /// <returns></returns>
        public static bool CheckAuthorize(string areaName,string controllerName,string actionName)
        {
            return CheckAuthorize(GetUrl(areaName, controllerName, actionName));
        }

        /// <summary>
        /// 获取菜单链接
        /// </summary>
        /// <param name="areaName"></param>
        /// <param name="controllerName"></param>
        /// <param name="actionName"></param>
        /// <returns></returns>
        private static string GetUrl(string areaName, string controllerName, string actionName)
        {
            StringBuilder moduleHref = new StringBuilder();
            if (!string.IsNullOrWhiteSpace(areaName))
            {
                moduleHref.Append("/");
                moduleHref.Append(areaName);
            }
            moduleHref.Append("/");
            moduleHref.Append(controllerName);
            moduleHref.Append("/");
            moduleHref.Append(actionName);
            return moduleHref.ToString();
        }
    }
    /// <summary>
    /// 全局键值
    /// </summary>
    public class GlobalKey
    {
        /// <summary>
        /// 验证码
        /// </summary>
        public static string ValidateCode { get; set; } = "ValidateCode";
        /// <summary>
        /// 登录用户信息
        /// </summary>
        public static string UserInfo { get; private set; } = "UserInfo";
        /// <summary>
        /// 模块信息
        /// </summary>
        public static string Module { get; private set; } = "Module";
        /// <summary>
        /// 模块信息超时时长
        /// </summary>
        public static int Module_TimeOut { get; private set; } = 30 * 60;
        /// <summary>
        /// 角色模块信息
        /// </summary>
        public static string RoleModule { get; private set; } = "RoleModule";
        /// <summary>
        /// 角色模块信息超时时长
        /// </summary>
        public static int RoleModule_TimeOut { get; private set; } = 30 * 60;
    }
    /// <summary>
    /// 全局配置
    /// </summary>
    public class GlobalConfig
    {
        /// <summary>
        /// 超级管理员用户名
        /// </summary>
        public static string AdminUserName { get; private set; } = "admin";
    }
}